Sum of left leaves¶
Time: O(N); Space: O(H); easy
Find the sum of all left leaves in a given binary tree.
Example 1:
Input: root = {TreeNode} [3,9,20,None,None,15,7]
3
/ \
9 20
/ \
15 7
Output: 24
Explanation:
There are two left leaves in the binary tree, with values 9 and 15 respectively.
Example 2:
Input: root = {TreeNode} [1,None,2,None,3]
Output: 0
Explanatinon:
1
\
2
\
3
[6]:
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
[7]:
class Solution1(object):
"""
Time: O(N)
Space: O(H)
"""
def sumOfLeftLeaves(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def sumOfLeftLeavesHelper(root, is_left):
if not root:
return 0
if not root.left and not root.right:
return root.val if is_left else 0
return sumOfLeftLeavesHelper(root.left, True) + \
sumOfLeftLeavesHelper(root.right, False)
return sumOfLeftLeavesHelper(root, False)
[8]:
s = Solution1()
root = TreeNode(3)
root.left = TreeNode(9)
root.right = TreeNode(20)
root.right.left = TreeNode(15)
root.right.right = TreeNode(7)
assert s.sumOfLeftLeaves(root) == 24
root = TreeNode(1)
root.right = TreeNode(2)
root.right.right = TreeNode(3)
assert s.sumOfLeftLeaves(root) == 0